﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_VBPQ_List
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub ShowData()
        Using data As New VSEntities
            'Show loai van ban
            Dim lvb = (From ck In data.VBPQLoaiVanBans Select ck).ToList
            If Not lvb Is Nothing Then
                drpType.DataSource = lvb
                drpType.DataTextField = "LoaiVanBan"
                drpType.DataValueField = "Id"
                drpType.DataBind()
                drpType.Items.Add(New ListItem("---Tất cả---", 0))
                drpType.SelectedValue = 0
            End If
            'Show co quan ban hanh da ton tai
            Dim cqbh = (From ck In data.VBPQCoQuanBHs Select ck).ToList
            If Not cqbh Is Nothing Then
                drpPromulgator.DataSource = cqbh
                drpPromulgator.DataTextField = "CoQuanBH"
                drpPromulgator.DataValueField = "Id"
                drpPromulgator.DataBind()
                drpPromulgator.Items.Add(New ListItem("---Tất cả---", 0))
                drpPromulgator.SelectedValue = 0
            End If
            'Show nguoi ky da ton tai                
            Dim nk = (From ck In data.VBPQNguoiKies Select ck).ToList
            If Not nk Is Nothing Then
                drpSigner.DataSource = nk
                drpSigner.DataTextField = "NguoiKy"
                drpSigner.DataValueField = "Id"
                drpSigner.DataBind()
                drpSigner.Items.Add(New ListItem("---Tất cả---", 0))
                drpSigner.SelectedValue = 0
            End If
            'Show trang thai da ton tai                
            Dim tt = (From ck In data.Status Select ck).ToList
            If Not tt Is Nothing Then
                drpStatus.DataSource = tt
                drpStatus.DataTextField = "Title"
                drpStatus.DataValueField = "StatusId"
                drpStatus.DataBind()
                drpStatus.Items.Add(New ListItem("---Tất cả---", -1))
                drpStatus.SelectedValue = -1
            End If
        End Using
    End Sub
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'xu ly jquery khi post back
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            ShowData()
            BindToGrid(1)
            If HasPermission(Function_Name.VBPQ, Session("RoleID"), 0, Audit_Type.Delete) = True Then
                btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
            Else
                btnDelete.Enabled = False
            End If
        End If
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, Optional ByVal strTitle As String = "", Optional ByVal strCode As String = "", Optional ByVal intType As Integer = 0, Optional ByVal intStatus As Integer = -1, Optional ByVal intCQBH As Integer = 0, Optional ByVal intSigner As Integer = 0, Optional ByVal strStartPublish As String = "", Optional ByVal strEndPublish As String = "")
        Using data As New VSEntities
            Dim arrSearch() As String = {iPage.ToString, _
                                         strTitle, _
                                         strCode, _
                                         intType.ToString, _
                                         intStatus.ToString, _
                                         intCQBH.ToString, _
                                         intSigner.ToString, _
                                         strStartPublish, _
                                         strEndPublish _
                                       }
            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim intOrderBy As Int32 = drpSort.SelectedValue
            Dim p As IList(Of uspVBPQDocumentselectAll_Result) = data.uspVBPQDocumentselectAll(IIf(String.IsNullOrEmpty(strTitle.Trim) = True, Nothing, strTitle.Trim), IIf(String.IsNullOrEmpty(strCode.Trim) = True, Nothing, strCode.Trim), IIf(intType = 0, Nothing, intType), intStatus, IIf(intCQBH = 0, Nothing, intCQBH), IIf(intSigner = 0, Nothing, intSigner), IIf(String.IsNullOrEmpty(strStartPublish) = True, Nothing, StringToDate(strStartPublish)), IIf(String.IsNullOrEmpty(strEndPublish) = True, Nothing, StringToDate(strEndPublish)), intOrderBy, iPage, intPag_Size).ToList
            Dim strKey_Name() As String = {"Id", "TrichYeu", "StatusId"}
            If p.Count > 0 Then
                'Tong so ban ghi
                hidCount.Value = p.FirstOrDefault.Total()
                Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            If (hidCount.Value > 0) Then
                lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
            Else
                lblTotal.Text = ""
            End If
        End Using

    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        'dang ky async ko postback
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(lnkTile.ToolTip, arrSearch(1), arrSearch(2), arrSearch(3), arrSearch(4), arrSearch(5), arrSearch(6), arrSearch(7), arrSearch(8))
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(hidCur_Page.Value, arrSearch(1), arrSearch(2), arrSearch(3), arrSearch(4), arrSearch(5), arrSearch(6), arrSearch(7), arrSearch(8))
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        arrSearch = ViewState("search")
        BindToGrid(hidCur_Page.Value, arrSearch(1), arrSearch(2), arrSearch(3), arrSearch(4), arrSearch(5), arrSearch(6), arrSearch(7), arrSearch(8))
    End Sub
#End Region
#Region "Event for control"
    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Dim data As New VSEntities
        intId = grdShow.DataKeys(hidID.Value)("Id").ToString

        ' Xoa bang trung gian VBPQCoQuanBanHanhDocument 
        Dim c = (From q In data.VBPQCoQuanBanHanhDocuments Where q.DocumentId = intId Select q).ToList
        If c.Count > 0 Then
            For i As Integer = 0 To c.Count - 1
                Try
                    data.VBPQCoQuanBanHanhDocuments.DeleteObject(c(i))
                    data.SaveChanges()
                Catch ex As Exception
                    Excute_Javascript("Alertbox('Xóa văn bản pháp quy thất bại. Văn bản này có chứa cơ quan ban hành.');", Me.Page, True)
                End Try
            Next
        End If
        ' Xoa bang trung gian VBPQChucDanhNguoiKies
        Dim b = (From q In data.VBPQChucDanhNguoiKies Where q.DocumentId = intId Select q).ToList
        If b.Count > 0 Then
            For i As Integer = 0 To b.Count - 1
                Try
                    data.VBPQChucDanhNguoiKies.DeleteObject(b(i))
                    data.SaveChanges()
                Catch ex As Exception
                    Excute_Javascript("Alertbox('Xóa văn bản pháp quy thất bại. Văn bản này có chức danh và người ký.');", Me.Page, True)
                End Try
            Next
        End If
        ' Xoa bang VBPQDocuments
        Dim a = (From q In data.VBPQDocuments Where q.Id = intId).FirstOrDefault
        If Not a Is Nothing Then
            Try
                data.VBPQDocuments.DeleteObject(a)
                data.SaveChanges()
                Insert_App_Log("Del VBPQ:" & a.TrichYeu & "", Function_Name.VBPQ, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
            Catch ex As Exception
                Excute_Javascript("Alertbox('Xóa thất bại');", Me.Page, True)
            End Try
        Else
            Excute_Javascript("Alertbox('Xóa thất bại');", Me.Page, True)
        End If
        BindToGrid()
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Dim data As New VSEntities
        Try
            For Each item As GridViewRow In grdShow.Rows
                Dim chkItem As New CheckBox
                chkItem = CType(item.FindControl("chkItem"), CheckBox)
                If chkItem.Checked Then
                    intTotal += 1
                    intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                    ' Xoa bang trung gian VBPQCoQuanBanHanhDocument 
                    Dim c = (From q In data.VBPQCoQuanBanHanhDocuments Where q.DocumentId = intId Select q).ToList
                    If c.Count > 0 Then
                        For i As Integer = 0 To c.Count - 1
                            Try
                                data.VBPQCoQuanBanHanhDocuments.DeleteObject(c(i))
                                data.SaveChanges()
                            Catch ex As Exception
                                Excute_Javascript("Alertbox('Xóa văn bản pháp quy thất bại. Văn bản này có chứa cơ quan ban hành.');", Me.Page, True)
                            End Try
                        Next
                    End If
                    ' Xoa bang trung gian VBPQChucDanhNguoiKies
                    Dim b = (From q In data.VBPQChucDanhNguoiKies Where q.DocumentId = intId Select q).ToList
                    If b.Count > 0 Then
                        For i As Integer = 0 To b.Count - 1
                            Try
                                data.VBPQChucDanhNguoiKies.DeleteObject(b(i))
                                data.SaveChanges()
                            Catch ex As Exception
                                Excute_Javascript("Alertbox('Xóa văn bản pháp quy thất bại. Văn bản này có chức danh và người ký.');", Me.Page, True)
                            End Try
                        Next
                    End If
                    ' Xoa bang VBPQDocuments
                    Dim a = (From q In data.VBPQDocuments Where q.Id = intId).FirstOrDefault
                    If Not a Is Nothing Then
                        Try
                            data.VBPQDocuments.DeleteObject(a)
                            data.SaveChanges()
                            intCount += 1
                            Insert_App_Log("Del VBPQ:" & a.TrichYeu & "", Function_Name.VBPQ, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                        Catch ex As Exception
                            Excute_Javascript("Alertbox('Xóa thất bại');", Me.Page, True)
                        End Try
                    End If
                End If
            Next
            If intCount > 0 Then
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
            Else
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End If
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
        End Try
        BindToGrid()
    End Sub
    Protected Sub grdShow_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdShow.PageIndexChanging
        grdShow.PageIndex = e.NewPageIndex
        BindToGrid()
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim status As Integer = grdShow.DataKeys(e.Row.RowIndex)("StatusId")
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            Dim chkItem As CheckBox = CType(e.Row.FindControl("chkItem"), CheckBox)
            'Permission
            If HasPermission(Function_Name.VBPQ, Session("RoleID"), status, Audit_Type.Delete) = True Then
                lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            Else
                lnkbtnDelete.Enabled = False
                chkItem.Enabled = False
            End If

            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            hplEdit.NavigateUrl = "../../Page/VBPQ/Edit.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
            'Permission
            hplEdit.Enabled = HasPermission(Function_Name.VBPQ, Session("RoleID"), status, Audit_Type.Edit)

            Dim hplTitle As HyperLink = CType(e.Row.FindControl("hplTitle"), HyperLink)
            hplTitle.NavigateUrl = "../../Page/VBPQ/Detail.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
            hplTitle.Text = grdShow.DataKeys(e.Row.RowIndex)("TrichYeu").ToString

            'Permission
            hplTitle.Enabled = HasPermission(Function_Name.VBPQ, Session("RoleID"), status, Audit_Type.ViewContent)

        End If
    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        BindToGrid(1)
    End Sub
    Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter.Click
        BindToGrid(1, txtTitleFilter.Text.Trim(), txtCodeFilter.Text.Trim(), drpType.SelectedValue, drpStatus.SelectedValue, drpPromulgator.SelectedValue, drpSigner.SelectedValue, txtStartPublish.Text.Trim(), txtEndPublish.Text.Trim())
    End Sub
    Protected Sub btnPublish_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPublish.Click
        Dim StringId As String = ""
        Dim intTotal As Integer
        Using data As New VSEntities
            For Each item As GridViewRow In grdShow.Rows
                Dim chkItem As New CheckBox
                chkItem = CType(item.FindControl("chkItem"), CheckBox)
                If chkItem.Checked Then
                    intTotal += 1
                    StringId += grdShow.DataKeys(item.RowIndex)("Id").ToString & ","
                    'Write Code here
                End If
            Next
            Response.Redirect("../../Page/VBPQ/ActionList.aspx?Id=" & StringId & "&NStatusId=3")
        End Using
    End Sub
    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        txtTitleFilter.Text = ""
        txtCodeFilter.Text = ""
        drpType.SelectedValue = 0
        drpPromulgator.SelectedValue = 0
        drpSigner.SelectedValue = 0
        drpStatus.SelectedValue = -1
        txtStartPublish.Text = ""
        txtEndPublish.Text = ""
        BindToGrid(1, txtTitleFilter.Text.Trim(), txtCodeFilter.Text.Trim(), drpType.SelectedValue, drpStatus.SelectedValue, drpPromulgator.SelectedValue, drpSigner.SelectedValue, txtStartPublish.Text.Trim, txtEndPublish.Text.Trim)
    End Sub
#End Region
End Class
